const { defineConfig } = require('@vue/cli-service')
const BodyParser = require('body-parser')
const Mock = require('mockjs')

const LoginUsers = [
  {
    id: 1,
    username: 'admin',
    password: '123456',
    avatar:
      'https://raw.githubusercontent.com/taylorchen709/markdown-images/master/vueadmin/user.png',
    name: '张某某'
  }
]

const Users = []

for (let i = 0; i < 86; i++) {
  Users.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      addr: Mock.mock('@county(true)'),
      'age|18-60': 1,
      birth: Mock.Random.date(),
      sex: Mock.Random.integer(0, 1)
    })
  )
}
let _Users = Users

module.exports = defineConfig({
  transpileDependencies: true,
  // publicPath: process.env.NODE_ENV === 'production' ? '/dianping/' : '/',
  devServer: {
    // 接口代理
    // proxy: {
    //   '/api': {
    //     target: 'http://localhost:3000',
    //     pathRewrite: {
    //       '^/api': '',
    //     },
    //   },
    // },
    // 模拟接口数据
    setupMiddlewares(middlewares, devServer) {
      devServer.app.use(BodyParser.json())

      // 1. 登陆接口
      devServer.app.post('/api/login', (req, res) => {
        const { username, password } = req.body

        let hasUser = LoginUsers.some((u) => {
          if (u.username === username && u.password === password) {
            user = JSON.parse(JSON.stringify(u))
            user.password = undefined
            return true
          }
        })

        if (hasUser) {
          res.json({ code: 200, msg: '请求成功', user })
        } else {
          res.status(401).json({ code: 500, msg: '账号或密码错误' })
        }
      })

      // 2. 获取用户列表接口
      devServer.app.get('/api/user/list', (req, res) => {
        let { name } = req.query
        let mockUsers = _Users.filter((user) => {
          if (name && user.name.indexOf(name) == -1) return false
          return true
        })
        res.json({ users: mockUsers })
      })

      // 3. 获取用户列表 分页
      devServer.app.get('/api/user/listpage', (req, res) => {
        let { page, name, size = 5 } = req.query
        let mockUsers = _Users.filter((user) => {
          if (name && user.name.indexOf(name) == -1) return false
          return true
        })
        let total = mockUsers.length
        mockUsers = mockUsers.filter(
          (u, index) => index < size * page && index >= size * (page - 1)
        )
        res.json({
          total: total,
          users: mockUsers
        })
      })

      // 4. 删除用户
      devServer.app.get('/api/user/remove/:id', (req, res) => {
        let { id } = req.params
        // console.log('params:', req.params)
        _Users = _Users.filter((u) => u.id !== id)
        // console.log(_Users, '_Users')
        res.json({
          code: 200,
          msg: '删除成功'
        })
      })

      // 5. 批量删除用户
      devServer.app.get('/api/user/batchremove', (req, res) => {
        let { ids } = req.query // ['','']
        ids = ids.split(',')
        _Users = _Users.filter((u) => !ids.includes(u.id))
        res.json({ code: 200, msg: '删除成功' })
      })

      // 6. 编辑用户
      devServer.app.post('/api/user/edit', (req, res) => {
        let { id, name, addr, age, birth, sex } = req.body
        _Users.some((u) => {
          if (u.id === id) {
            u.name = name
            u.addr = addr
            u.age = age
            u.birth = birth
            u.sex = sex
            return true
          }
        })
        res.json({ code: 200, msg: '编辑成功' })
      })

      // 7. 新增用户
      devServer.app.post('/api/user/add', (req, res) => {
        let { name, addr, age, birth, sex } = req.body
        _Users.push({
          name: name,
          addr: addr,
          age: age,
          birth: birth,
          sex: sex
        })
        res.json({ code: 200, msg: '新增成功' })
      })

      return middlewares
    }
  }
})
